package com.si.control.action;

import java.awt.image.BufferedImage;
import java.util.List;

import javax.swing.JOptionPane;

import com.si.control.ActionHandler;
import com.si.ui.HiResCanvas;
import com.si.ui.enumn.ECollageAlgorithm;
import com.si.ui.enumn.EHiResCanvas;

public class HiResAction extends ActionHandler<EHiResCanvas> implements IAction<List<BufferedImage>, Object> {

	private final IAction<BufferedImage, Object> saveAction;

	private List<BufferedImage> list;
	private HiResCanvas canvas;
	private CollageAction action;
	private BufferedImage image;

	public HiResAction() {
		this.saveAction = new SaveImageAction();
	}

	@Override
	public Object perform(List<BufferedImage> argument) throws Exception {
		this.list = argument;
		if(this.list == null || this.list.isEmpty()) {
			JOptionPane.showMessageDialog(null, "No images to collage.");
			return null;
		}
		// Size.
		final String wStr = JOptionPane.showInputDialog(null, "Please enter output width:");
		if(wStr == null) return null;
		final Integer width = Integer.valueOf(wStr);
		if(width == null) return null;
		final String hStr = JOptionPane.showInputDialog(null, "Please enter output height:");
		if(hStr == null) return null;
		final Integer height = Integer.valueOf(hStr);
		if(height == null) return null;
		// Algorithm.
		final ECollageAlgorithm algorithm = (ECollageAlgorithm)JOptionPane.showInputDialog(null, "Please select collaging algorithm",
				"Algorithm Selection", JOptionPane.PLAIN_MESSAGE, null, ECollageAlgorithm.values(), ECollageAlgorithm.values()[0]);
		if(algorithm == null) return null;
		// Generate.
		switch(algorithm) {
		case RandomCollage:
			this.action = new RandomCollageAction();
			this.action.setWidth(width);
			this.action.setHeight(height);
			this.image = this.action.perform(this.list);
			break;
		case FourLay:
			this.action = new FourLayCollageAction();
			this.action.setWidth(width);
			this.action.setHeight(height);
			this.image = this.action.perform(this.list);
			break;
		case PreservedCollage:
			this.action = new PreservedCollageAction();
			this.action.setWidth(width);
			this.action.setHeight(height);
			this.image = this.action.perform(this.list);
			break;
		}
		if(this.image == null) return null;
		// Set to canvas.
		this.canvas = new HiResCanvas(width, height);
		this.canvas.setImage(this.image);
		this.canvas.btnRefresh.addActionListener(this);
		this.canvas.btnSave.addActionListener(this);
		this.canvas.setVisible(true);
		return null;
	}

	@Override
	protected void handle(final EHiResCanvas command) {
		try {
			switch(command) {
			case HiRes_Refresh:
				this.image = this.action.perform(this.list);
				this.canvas.setImage(this.image);
				break;
			case HiRes_Save: this.saveAction.perform(this.image); break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected EHiResCanvas parse(final String str) {
		return EHiResCanvas.valueOf(str);
	}
}
